define(["controller", "coordtransform"], function (c, coordtransform) {
    var server = c.playbackserver || "ws://g.air-cloud.cn:220/";
    var token = c.getToken() || "MSNBRE1JTiMxNDUyMDA0NzE5IzJmOWRmOGZmZTc1NTA3NzMxMGNmM2ZjNWIwM2FmMTVmZTdlMGExNGJjZGViYzcwZGQ1ODcwMTAxYjEzMTgzM2Q=";

    var frame_num = 20;
    var points = [];
    var speed = 1.0;
    var id;
    var cur_pos;

    function speedup() {
        speed *= 2;
        speed = Math.min(32.0, speed);
    }

    function speeddown() {
        speed /=2;
        speed = Math.max(1.0, speed);
    }

    function getspeed (){
        return speed
    }

    function move(ts) {
        if (ts < parseInt(points.d[0].ts) || ts > parseInt(points.d[points.d.length - 1].ts)){
            alert("超出范围");
            return;
        }
        for (var i in points.d) {
	    i = parseInt(i);
            if (points.d[i].ts <= ts && points.d[i + 1].ts > ts) {
                points.t = i;
                points.t1 = (ts - points.d[points.t].ts) * frame_num;
                break;
            }
        }
    }

    function consumer_point() {
        if (!(points.d && points.d.length > 0)) {
            alert("没有正确的数据!");
            return;
        }
        var data = points;
        cur_pos = null;
        if (data.d[data.t + 1]) {
            var diff_ts = data.d[data.t + 1].ts - data.d[data.t].ts;
            if (diff_ts <= 0) {
                data.t1 = 0;
                cur_pos = data.d[++data.t];
            }
            else {
                var sum_frame = frame_num * diff_ts;
                var k = data.t1 / sum_frame;
                var diff_lat = data.d[data.t + 1].lat - data.d[data.t].lat;
                var diff_lng = data.d[data.t + 1].lng - data.d[data.t].lng;
                data.t1 += speed;
                if (data.t1 >= sum_frame) {
                    ++data.t;
                    data.t1 = 0;
                }
                else {
                    cur_pos = {
                        "id": id,
                        "lat": data.d[data.t].lat + diff_lat * k,
                        "lng": data.d[data.t].lng + diff_lng * k,
                        "height": data.d[data.t].height,
                        "speed": data.d[data.t].speed,
                        "course": data.d[data.t].course
                    };
                }
                ;
            }
        }
        if (!cur_pos) {
            cur_pos = data.d[data.t];
        }
        return cur_pos;
    }

    function get_track()
    {
        var line = [];
        var data = points;
        for (var i = 0; i <= data.t && data.d[i]; ++i)
        {
            line.push({lng:data.d[i].lng, lat:data.d[i].lat});
        }
        line.push({lng:cur_pos.lng, lat:cur_pos.lat});
        return line;
    }

    function connect(fid, st, ed, fnObj) {
        var ws = new WebSocket(server + token + "/" + fid + "/" + st + "/" + ed);
        if (!ws) {
            alert("您的浏览器版本太低,不支持WebSocket,建议使用最新版本的Chrome Firefox或者IE");
            window.opener = null;
            window.open('', '_self');
            window.close();
        }
        ws.binaryType = "arraybuffer";
        ws.onopen = function () {
            console.log('websocket connected', server);
            //连接服务器成功,可以有回调
            points = {"t": 0, "t1": 0, "d": []};
            speed = 1.0;
            id = fid;
            cur_pos = null;
            fnObj.onopen();
        };
        ws.onerror = function (error) {
            console.log("websocket", error);
            //如果有错误,这里应该有回调
            fnObj.error();
        };
        ws.onmessage = function (a) {
            var LE = true;
            var d = new DataView(a.data);
            if (d.byteLength % 24 == 0) {
                for (var i = 0; i < d.byteLength;) {
                    var ts = d.getUint32(i, LE);
                    i += 4;
                    var lat = (d.getInt32(i, LE) / 1e7);
                    i += 4;
                    var lng = (d.getInt32(i, LE) / 1e7);
                    i += 4;
                    var height = (d.getInt32(i, LE) / 1e3).toFixed(1);
                    i += 4;
                    var speed = (d.getUint32(i, LE) / 1e2).toFixed(1);
                    i += 4;
                    var course = (d.getUint32(i, LE) / 1e2).toFixed(1);
                    i += 4;
                    var lnglat = coordtransform.wgs84togcj02(lng * 1, lat * 1);
                    var tmp = {
                        "id": fid,
                        "ts": ts,
                        "lat": lnglat[1],
                        "lng": lnglat[0],
                        "height": height,
                        "speed": speed,
                        "course": course
                    };
                    points.d.push(tmp);
                }
            }
            else {
                console.log("package length error ", d.byteLength, len);
            }
        };
        ws.onclose = function () {
            console.log('websocket disconnected');
            ws = null;
            points.d.sort(function (a, b) {
                return a.ts - b.ts;
            });
            if (points.d.length > 1) {
                points.d.unshift(points.d[0]);
                points.d[0].ts = st;
                points.d[0].speed = 0;
                points.d.push(points.d[points.d.length - 1]);
                points.d[points.d.length - 1].ts = ed;
            }
            for (var i = 1; i < points.d.length;) {
                if (i > 0 && points.d[i].ts == points.d[i - 1].ts) {
                    points.d.splice(i, 1);
                }
                else {
                    ++i;
                }
            }
            //数据接收完毕,在这里进行回调操作
            id = fid;
            fnObj.success(points);
        };
    }


    return {
        getspeed: getspeed,
        frame_num: frame_num,
        consumer_point: consumer_point,
        speedup: speedup,
        speeddown: speeddown,
        connect: connect,
        move: move,
        get_track: get_track
    };

});
